import frappe
from frappe.model.document import Document
from frappe.utils.data import now_datetime
from zy_packlist.zy_packlist.doctype.packing_list.packing_list import get_packing_items_ledgers,add_packing_items_ledgers

class PackListDoc(Document):

	status_map={0:'Draft',1:"Submitted",2:"Cancelled"}
    
	def validate(self):
		self.set_packing_item_bundle()
		self.validate_posting_time()
		self.status=self.status_map[self.docstatus]

	def set_packing_item_bundle(self):
		for row in self.items:
			if row.packing_list_items:
				frappe.get_doc("Packing List", row.packing_list_items).set_packing_and_voucher_values(self, row)
	
	def validate_posting_time(self):
		now = now_datetime()
		self.posting_date = now.strftime("%Y-%m-%d")
		self.posting_time = now.strftime("%H:%M:%S.%f")

	def on_submit(self):
		for row in self.items:
			if row.packing_list_items:
				frappe.get_doc("Packing List", row.packing_list_items).submit()
	
	def before_save(self):
		pass


	def on_update(self):
		if self.docstatus==0:
			currency_changed = self.has_value_changed("currency")
			# frappe.msgprint('我有没有执行啊'+str(currency_changed))
			if currency_changed:
				for row in self.items:
					if row.packing_list_items:
						doc=frappe.get_doc("Packing List", row.packing_list_items)
						doc.currency=self.currency
						doc.save()

		

	def  on_cancel(self):
		# frappe.msgprint('我有没有执行啊')
		self.ignore_linked_doctypes = ["Packing List"]
			
		for row in self.get('items'):
			if row.packing_list_items:
				frappe.get_doc("Packing List", row.packing_list_items).cancel()
				row.db_set("packing_list_items", None)
		
		self.db_set({'status':self.status_map[self.docstatus]})
	

	
	def on_trash(self):
		
		# self.ignore_linked_doctypes = ["Packing List"]
		for row in self.items:
			row.db_set("packing_list_items", None)
			if row.old_packing_list_items:
				frappe.get_doc("Packing List", row.old_packing_list_items).delete()

